<template>
  <div class="spec-group">
    <!--    spu参数配置-规格组渲染组件-->
    <Collapse v-model:activeKey="activeKey">
      <CollapsePanel key="1">
        <template #header>
          <div class="custom-header">
            <div class="group-form">
              <Form
                ref="formRef"
                :model="formModel"
                :label-col="{ span: 8 }"
                :wrapper-col="{ span: 16 }"
              >
                <Row>
                  <Col span="6" v-for="item in specGroupFormSchema" :key="item.field">
                    <FormItem
                      :name="item.field"
                      :label="item.label"
                      :rules="
                        item.required
                          ? [
                              {
                                required: true,
                                trigger: ['blur', 'change'],
                                message: `${item.label}必填！`,
                              },
                            ]
                          : undefined
                      "
                      @click.stop
                    >
                      <div
                        @mouseenter="handleSortableDisabled(true)"
                        @mouseleave="handleSortableDisabled(false)"
                      >
                        <Input
                          v-if="item['component'] === 'Input'"
                          v-model:value="formModel[item.field]"
                        />
                        <InputNumber
                          v-if="item['component'] === 'InputNumber'"
                          v-model:value="formModel[item.field]"
                        />
                        <Select
                          v-if="item['component'] === 'Select'"
                          v-model:value="formModel[item.field]"
                          :allowClear="true"
                        >
                          <SelectOption
                            v-for="option in item.componentProps
                              ? item.componentProps['options']
                              : []"
                            :key="option.value"
                            :value="option.value"
                            >{{ option.label }}</SelectOption
                          >
                        </Select>
                      </div>
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <Icon
              size="20"
              class="remove-btn"
              icon="clarity:remove-solid"
              @click.stop="handleRemove"
              @mouseenter="handleSortableDisabled(true)"
              @mouseleave="handleSortableDisabled(false)"
            />
            <div class="action-btn">
              <Button
                :type="'primary'"
                @click.stop="handleRelevanceOprValue"
                @mouseenter="handleSortableDisabled(true)"
                @mouseleave="handleSortableDisabled(false)"
                >{{ optValueName || '关联规格值' }}</Button
              >
              <Button
                :type="'primary'"
                style="margin-left: 10px"
                @click="handleChooseBizMetaAttr"
                @mouseenter="handleSortableDisabled(true)"
                @mouseleave="handleSortableDisabled(false)"
                >选择元属性</Button
              >
            </div>
          </div>
        </template>

        <SpuSpec ref="spuSpecRef" :if-child="ifChild" :spu-config="specItem" />

        <div style="margin-top: 15px" class="flex-row-center-start">
          <Button :type="'primary'" @click="handleAddSpec(GROUP)">添加规格组</Button>
          <Button :type="'primary'" style="margin: 0 20px 0 10px" @click="handleAddSpec(ATTR)"
            >添加规格项</Button
          >
          <div>路径：{{ pathName }}</div>
        </div>
      </CollapsePanel>
    </Collapse>

    <BizMetaAttrModal :if-single="true" @register="registerModal" @ok="handleActionOk" />
  </div>
</template>

<script setup lang="ts">
  import { computed, inject, ref } from 'vue';
  import Icon from '@/components/Icon/Icon.vue';
  import { useModal } from '@/components/Modal';
  import { useMessage } from '@/hooks/web/useMessage';
  import { SpuSpecificationTypeEnum } from '@/enums/spuEnum';
  import { SpuSpecModel } from 'mc-c2b2m-operator-api/types/spu';
  import { specGroupFormSchema } from '@/views/spu/spu/setting/data';
  import SpuSpec from '@/views/spu/spu/setting/components/SpuSpec.vue';
  import {
    Row,
    Col,
    Form,
    Input,
    Button,
    Select,
    FormItem,
    Collapse,
    InputNumber,
    SelectOption,
    CollapsePanel,
  } from 'ant-design-vue';
  import BizMetaAttrModal from '@/components/BizMetaAttrModal/Index.vue';

  const props = defineProps({
    // 规格项数据源
    specItem: {
      type: Object as PropType<SpuSpecModel>,
      default: () => {
        return {};
      },
    },
  });

  const emits = defineEmits([
    'save',
    'remove',
    'addSpec',
    'update:specItem',
    'chooseBizMetaAttr',
    'relevanceOprValue',
  ]);

  const formRef = ref();
  const spuSpecRef = ref();
  const { createConfirm } = useMessage();
  const { ATTR, GROUP } = SpuSpecificationTypeEnum;
  const activeKey = ref<string[]>(['1']);

  const [registerModal, { openModal, closeModal }] = useModal();

  // 关联规格值名称
  const optValueName = computed(() => {
    return props.specItem?.optValueList?.[0]?.displayName;
  });
  // 关联规格值操作
  function handleRelevanceOprValue() {
    openModal(true, {
      ...props.specItem?.optValueList?.[0],
      emitData: { ifRelevanceOprValue: true },
    });
  }
  // 选择元属性操作
  function handleChooseBizMetaAttr() {
    openModal(true, { ...props.specItem });
  }
  // 关联规格值/选择元属性操作完成
  function handleActionOk(data: any, emitData: any) {
    closeModal();
    const { ifRelevanceOprValue } = emitData || {};
    const { id, cnName, uiComponentCodeList } = data?.[0] || {};
    if (ifRelevanceOprValue) {
      emits(
        'relevanceOprValue',
        id && cnName
          ? [
              {
                bizMetaAttrId: id,
                displayName: cnName,
                spuSpecId: props.specItem.id,
                sort: 1,
              },
            ]
          : [],
      );
    } else {
      const uniCom = uiComponentCodeList?.[0] || '';
      const model = {
        bizMetaAttrId: id,
        displayName: cnName,
        uiComponent: uniCom,
      };
      emits('chooseBizMetaAttr', model);
    }
  }

  const handlePathName: any = inject('handlePathName');
  // 路径
  const pathName = computed(() => {
    const { id, displayName } = props.specItem;
    const pathList = handlePathName?.(id);
    return `${pathList.join('/')}` + displayName;
  });
  // 表单数据模型
  const formModel = computed({
    get: () => props.specItem,
    set: (val) => emits('update:specItem', val),
  });
  // 是否含有子规格配置
  const ifChild = computed(() => {
    return !!props.specItem?.childSpuSpecList?.length;
  });
  // 组内添加规格配置
  function handleAddSpec(type: SpuSpecificationTypeEnum) {
    emits('addSpec', type);
  }
  // 移除规格组
  function handleRemove() {
    createConfirm({
      title: '提示',
      iconType: 'warning',
      content: '是否确认删除？',
      onOk: () => {
        emits('remove');
      },
    });
  }

  // 拖拽禁用
  const handleSortableDisabled: any = inject('handleSortableDisabled');

  defineExpose({ formRef, spuSpecRef });
</script>

<style scoped lang="less">
  :deep(.ant-form-item) {
    margin-bottom: 15px;
  }
  :deep(.ant-collapse-header) {
    padding-bottom: 0 !important;
  }
  .custom-header {
    width: 100%;
    position: relative;
    .group-form {
      width: 90%;
      margin-left: 10px;
    }
    .remove-btn {
      top: 0;
      right: 0;
      position: absolute;
    }
    .action-btn {
      right: 0;
      bottom: 10px;
      position: absolute;
    }
  }
</style>
